import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {

    public static void main(String[] args) {
        try {
            Selector selector = Selector.open();
            {
                ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                serverSocketChannel.configureBlocking(false);
                ServerSocket serverSocket = serverSocketChannel.socket();
                InetSocketAddress inetSocketAddress = new InetSocketAddress(8888);
                serverSocket.bind(inetSocketAddress);

                SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            }

            while(true){

                int num = selector.select();
//                System.out.println("num="+num);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while(iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    if((selectionKey.readyOps()&SelectionKey.OP_ACCEPT)==SelectionKey.OP_ACCEPT){
                        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);

                        socketChannel.register(selector,SelectionKey.OP_READ);
                        System.out.println( "Got connection from "+serverSocketChannel );
                        iterator.remove();
                    }else if((selectionKey.readyOps()&SelectionKey.OP_READ)==SelectionKey.OP_READ){

                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        while(true){
                            byteBuffer.clear();
                            int r = socketChannel.read(byteBuffer);
                            if(r<=0){
                                break;
                            }
                            byteBuffer.flip();
                            while(byteBuffer.hasRemaining()){
                                System.out.println(byteBuffer.get());
                            }
                        }
                    }
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
